package com.sz.youban.dt.service.utils;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;

/**
 * 日期格式
 */
public class DateUtil {

    /**
     * 获取当前时间，格式yyyyMMdd
     * @return
     */
    public static String getCurDay(){

        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    /**
     * 获取当前时间，格式yyyyMM
     * @return
     */
    public static String getCurMonth(){

        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMM");
        String dateString = formatter.format(currentTime);
        return dateString;
    }


    /**
     * 获取当前时间，格式dd，如28
     * @return
     */
    public static String getCurDayInMonth(){

        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("dd");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    /**
     * 字符串转时间
     * @param str       时间字符串，如 2017-04-15 19:00:00、2017-04-15
     * @param format    格式，如yyyy-MM-dd HH:mm:ss、yyyy-MM-dd
     * @return
     */
    public static Date str2Date(String str, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date d = null;
        try {
            d = sdf.parse(str);
        } catch (ParseException e) {
        }
        return d;
    }

    /**
     * 时间转字符串
     * @param date      时间
     * @param format    格式，如yyyy-MM-dd HH:mm:ss、yyyy-MM-dd
     * @return
     */
    public static String date2Str(Date date, String format){

        SimpleDateFormat formatter = new SimpleDateFormat(format);
        String dateString = formatter.format(date);
        return dateString;
    }

    /**
     * Date对象转LocalDateTime对象
     * @param date      时间
     * @return
     */
    public static LocalDateTime date2LocalDateTime(Date date){

        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();

        LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
        return localDateTime;
    }

    /**
     * Date对象转LocalDateTime对象
     * @param localDateTime      时间
     * @return
     */
    public static Date localDateTime2Date(LocalDateTime localDateTime){

        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime zdt = localDateTime.atZone(zoneId);

        Date date = Date.from(zdt.toInstant());

        System.out.println("LocalDateTime = " + localDateTime);
        System.out.println("Date = " + date);
        return date;
    }

}

